#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

# imports
from dbinter import *
from util import *
from oaicookie import *
from time import time
import cgi
from directory import *
from urlcheck import *
from auth import *
from terms import shorten

__all__ = ['pullValue', 'suggest']

def pullValue(cgiparams, field):
	if cgiparams.has_key(field):
		return cui(cgiparams[field].value)
	return ''

class suggest:
	"""
	The suggest class handles the output of the suggest page.
	"""
	def __init__(self):
		self.params = {}
		self.suggest = {}

	def process(self):
		# pull cgi
		self.params = cgi.FieldStorage()

		# print header
		outbit('pg_header_4')

		outbit('pg_title_1')

		outbit('pg_bar_short')

		# check if this is a submit
		if self.recordSubmit() == 1: return

		# make the page
		print '<div align="center" class="margin2em">'
		print '<b>DIRECTORY SUGGESTION PAGE</b><br><br>'
		# database
		db = oai_db()
		db.connect()

		#is this an edit submission?
		try:
			editRec = int(pullValue(self.params,'edit'))
			self.edit(editRec)

		except: pass

		# is this a modification?
		modRec = pullValue(self.params,'m')
		if len(modRec) == 32:
			self.modify(modRec)

		# new suggestion
		else:
			# get record info
			sRec = pullValue(self.params,'r')	# record suggestion
			sDir = pullValue(self.params,'d')	# directory/link suggestion
			if sRec != '': self.suggest['recHash'] = sRec
			elif sDir != '': self.suggest['parentHash'] = sDir

			# current info + actions
			if self.currentInfo(db) != 1:
				# directory navigation, only print if recHash is valid
				if self.suggest.has_key('recHash'):
					self.directoryNav('ROOT')
				else:
					self.directoryNav(self.suggest['parentHash'])
		
		db.disconnect()
		print '</div>'
		
		# print footer
		outbit('pg_footer_3')

	def recordSubmit(self):
		# if this is a submit, record and return 1
		self.suggest['title'] = pullValue(self.params,'title')

		# if title is empty or not submitted, then this is not a submit
		if len(self.suggest['title']) < 1: return 0

		# edit field means this is an editor editing a submission
		self.suggest['edit'] = pullValue(self.params,'edit')
		# type field is for new submissions
		self.suggest['type'] = pullValue(self.params,'type')
		# modify is for modify/delete submissions
		self.suggest['modify'] = pullValue(self.params,'modact')

		# remaining fields
		self.suggest['description'] = pullValue(self.params,'description')
		self.suggest['url'] = pullValue(self.params,'url')
		self.suggest['parent'] = pullValue(self.params,'parent')
		self.suggest['record'] = pullValue(self.params,'record')
		self.suggest['target'] = pullValue(self.params,'target')
		self.suggest['email'] = pullValue(self.params,'email')

		try:
			if len(self.suggest['edit']) > 0:
				# edit
				self.submitEdit()
			elif len(self.suggest['modify']) > 0:
				# modify/deletion
				self.submitMod()
			elif len(self.suggest['type']) > 0:
				# new suggestion
				self.submitNew()
			else: raise
		except:
			outbit('pg_suggest_failed_1')
		# print footer
		outbit('pg_footer_3')
		return 1

	def edit(self, suggID):
		# modify recHash
		record = quick_query("SELECT * FROM directorySubmissions WHERE recID = '%s';" % suggID)
		if len(record) < 1: return	# invalid rec
		record = record[0]

		# set up form data
		type = getDirType(record)
		if record['isLink'] == 'Y':
			# reverse for link
			data = (record['entryTitle'],record['entryDescription'],'','','checked',record['entryLink'],record['recHash'],record['parentHash'],record['targetHash'],record['optionalEmail'],record['recID'],record['isModify'])
		else:
			# set up selected radio box
			if record['isRecord'] == 'Y':
				chk1 = 'checked'
				chk2 = ''
			else:
				chk1 = ''
				chk2 = 'checked'
			
			data = (record['entryTitle'],record['entryDescription'],chk1,chk2,'',record['entryLink'],record['recHash'],record['targetHash'],record['parentHash'], record['optionalEmail'],record['recID'],record['isModify'])

		# print the form
		outbit('pg_suggest_edit_1',data)
		# print the directory
		self.directoryNav(record['parentHash'])

	def modify(self, recHash):
		# modify recHash
		record = quick_query("SELECT * FROM directoryTree WHERE recHash = '%s';" % recHash)
		if len(record) < 1: return	# invalid rec
		record = record[0]

		# set up form data
		type = getDirType(record)
		if record['isLink'] == 'Y':
			# reverse for link
			data = (record['entryTitle'],record['entryDescription'],type,record['entryLink'],record['recHash'],record['parentHash'],record['targetHash'])
		else:
			data = (record['entryTitle'],record['entryDescription'],type,record['entryLink'],record['recHash'],record['targetHash'],record['parentHash'])
		# print the form
		outbit('pg_suggest_modify_1',data)
		# print the directory
		self.directoryNav(record['parentHash'])

	def submitMod(self):
		# marked as submitted, record suggestion and acknowledge
		# connect to db
		db = oai_db()
		db.connect()
		
		# set up the data to insert
		insertDict = {}
		insertDict['recHash'] = self.suggest['record'][:32]
		insertDict['parentHash'] = self.suggest['parent'][:32]
		insertDict['targetHash'] = self.suggest['target'][:32]
		insertDict['isModify'] = 'Y'
		if self.suggest['type'] == 'Record': insertDict['isRecord'] = 'Y'
		else: insertDict['isRecord'] = 'N'
		if self.suggest['type'] == 'Directory': insertDict['isDirectory'] = 'Y'
		else: insertDict['isDirectory'] = 'N'
		if self.suggest['type'] == 'Link': insertDict['isLink'] = 'Y'
		else: insertDict['isLink'] = 'N'
		insertDict['entryLink'] = self.suggest['url']
		insertDict['entryDescription'] = self.suggest['description']
		insertDict['entryTitle'] = self.suggest['title']
		insertDict['optionalEmail'] = self.suggest['email']

		# if entry is a link
		if insertDict['isLink'] == 'Y':
			# swaping hashes - because for links hashes are passed in backwards
			pH = insertDict['parentHash']
			insertDict['parentHash'] = insertDict['targetHash']
			insertDict['targetHash'] = pH
			insertDict['entryLink'] = ''
			# do not recalc recHash at this time

		# if entry is a directory
		elif insertDict['isDirectory'] == 'Y':
			# do not recalc recHash at this time
			insertDict['entryLink'] = ''
		
		# create the query
		db.insert('directorySubmissions',insertDict)
		db.disconnect()

		# print confirmation
		outbit('pg_suggest_confirm_1')

	def submitEdit(self):
		# edit by editor, authenticate and update
		success, message = authenticate()
		if success != 1:
			print message
			raise

		self.suggest['edit'] = int(self.suggest['edit'])

		# connect to db
		db = oai_db()
		db.connect()
		
		# set up the data to insert
		insertDict = {}
		insertDict['recHash'] = self.suggest['record'][:32]
		insertDict['parentHash'] = self.suggest['parent'][:32]
		insertDict['targetHash'] = self.suggest['target'][:32]
		insertDict['isModify'] = pullValue(self.params,'modify')
		if self.suggest['type'] == 'record': insertDict['isRecord'] = 'Y'
		else: insertDict['isRecord'] = 'N'
		if self.suggest['type'] == 'directory': insertDict['isDirectory'] = 'Y'
		else: insertDict['isDirectory'] = 'N'
		if self.suggest['type'] == 'link': insertDict['isLink'] = 'Y'
		else: insertDict['isLink'] = 'N'
		insertDict['entryLink'] = self.suggest['url']
		insertDict['entryDescription'] = self.suggest['description']
		insertDict['entryTitle'] = self.suggest['title']
		insertDict['optionalEmail'] = self.suggest['email']

		# if entry is a link
		if insertDict['isLink'] == 'Y':
			# swaping hashes - because for links hashes are passed in backwards
			pH = insertDict['parentHash']
			insertDict['parentHash'] = insertDict['targetHash']
			insertDict['targetHash'] = pH
			insertDict['entryLink'] = ''
			insertDict['recHash'] = directoryHash(insertDict['parentHash'],insertDict['entryTitle'])

		# if entry is a directory
		elif insertDict['isDirectory'] == 'Y':
			insertDict['recHash'] = directoryHash(insertDict['parentHash'],insertDict['entryTitle'])
			insertDict['entryLink'] = ''

		# create the query
		db.query('DELETE FROM directorySubmissions WHERE recID = %s;' % self.suggest['edit'])
		db.insert('directorySubmissions',insertDict)
		db.disconnect()

		# print confirmation
		outbit('pg_suggest_confirm_2')

	def submitNew(self):
		# marked as submitted, record suggestion and acknowledge
		# connect to db
		db = oai_db()
		db.connect()
		
		# set up the data to insert
		insertDict = {}
		insertDict['recHash'] = self.suggest['record'][:32]
		insertDict['parentHash'] = self.suggest['parent'][:32]
		insertDict['targetHash'] = self.suggest['target'][:32]
		if self.suggest['type'] == 'record': insertDict['isRecord'] = 'Y'
		else: insertDict['isRecord'] = 'N'
		if self.suggest['type'] == 'directory': insertDict['isDirectory'] = 'Y'
		else: insertDict['isDirectory'] = 'N'
		if self.suggest['type'] == 'link': insertDict['isLink'] = 'Y'
		else: insertDict['isLink'] = 'N'
		insertDict['entryLink'] = self.suggest['url']
		insertDict['entryDescription'] = self.suggest['description']
		insertDict['entryTitle'] = self.suggest['title']
		insertDict['optionalEmail'] = self.suggest['email']

		# in entry is a record
		if insertDict['isRecord'] == 'Y':
			# no need for a target hash
			insertDict['targetHash'] = ''
			# check to see if record hash is present
			if insertDict['recHash'] == '':
				# then this is an external link, generate a hash
				insertDict['isExternal'] = 'Y'
				# prehashed -> EXTERNAL.(randomstring).url
				rstr = genRandStr(16)
				prehash = 'EXTERNAL' + rstr + insertDict['entryLink']
				insertDict['recHash'] = make_hash(prehash)

		# if entry is a link
		elif insertDict['isLink'] == 'Y':
			# swaping hashes - because for links hashes are passed in backwards
			pH = insertDict['parentHash']
			insertDict['parentHash'] = insertDict['targetHash']
			insertDict['targetHash'] = pH
			insertDict['entryLink'] = ''
			insertDict['recHash'] = directoryHash(insertDict['parentHash'],insertDict['entryTitle'])

		# if entry is a directory
		elif insertDict['isDirectory'] == 'Y':
			insertDict['recHash'] = directoryHash(insertDict['parentHash'],insertDict['entryTitle'])
			insertDict['entryLink'] = ''

		# create the query
		db.insert('directorySubmissions',insertDict)
		db.disconnect()

		# print confirmation
		outbit('pg_suggest_confirm_1')

	def currentInfo(self, passed_db):
		if self.suggest.has_key('recHash'):
			# print current suggested record and option to submit to current directory
			record = passed_db.query_dict("SELECT * FROM harvestSearch WHERE recHash = '%s';" % (self.suggest['recHash']) )
			if len(record) < 1:
				print "Record not found."
				return 1

			# hash is unique so only one record is returned
			record = record[0]

			data = (uni2asc(record['mTitle'])[:120].replace('\n',' '),uni2asc(record['mDescription'])[:300],'checked','', checkUrl(record,1),record['recHash'],'','ROOT')
			outbit('pg_suggest_form_1', data)

		elif self.suggest.has_key('parentHash'):
			# print blank form for directory suggestion 
			data = ('','','','checked','','',self.suggest['parentHash'],self.suggest['parentHash'])
			outbit('pg_suggest_form_1', data)

		else:
			return 1
		return 0 

	def directoryNav(self,parent):
		# print directory navigation
		print """<span class="smallish">
		<i><b>For records & directories</b></i>: Please navigate the directory to where
		you want the record to be placed. <br>
		<i><b>For links</b></i>: The link will be placed in the directory where you
		clicked	'Suggest'. Please navigate to the directory where you want it to link
		to below.</span>"""
		print '<div id="parentSelector">'
		printDirectory(parent,1)
		print '</div>'

# begin execution
def suggest_main():
	"""
	Returns: None
	
	Main function. This is called upon execution.
	"""
	print "Content-type: text/html\n\n"
	page = suggest()
	data = page.process()

if __name__ == '__main__' or __name__ == 'suggest':
	run = suggest_main()

#eof

